/*
 * @Author: aggfb 714740235@qq.com
 * @Date: 2024-04-16 22:43:31
 * @LastEditors: aggfb 714740235@qq.com
 * @LastEditTime: 2024-04-17 22:32:10
 * @FilePath: \stepper_motor\bsp\bsp_timer.c
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include "bsp_timer.h"

/**
 * 输入捕获(脉冲信号检测)
*/
void bsp_timer1_init(void)
{
    timer_ic_parameter_struct timer_icinitpara;
    timer_parameter_struct timer_initpara;
 
    rcu_periph_clock_enable(RCU_GPIOA);
    rcu_periph_clock_enable(RCU_AF);
    rcu_periph_clock_enable(RCU_TIMER1);
 
    //GPIO
    gpio_init(GPIOA, GPIO_MODE_IN_FLOATING, GPIO_OSPEED_50MHZ, GPIO_PIN_0);
 
    /* TIMER1 configuration */
    timer_initpara.prescaler         = (120 - 1);           //定时器的时钟频率是120MHz,预分频120-1,120/120=1MHZ
    timer_initpara.alignedmode       = TIMER_COUNTER_EDGE;  //对齐模式
    timer_initpara.counterdirection  = TIMER_COUNTER_UP;    //向上计数
    timer_initpara.period            = 65535;               //重载值,周期
    timer_initpara.clockdivision     = TIMER_CKDIV_DIV1;    //不分频
    timer_initpara.repetitioncounter = 0;                   //重复计数
    timer_init(TIMER1, &timer_initpara);
 
    /* TIMER1  configuration */
    /* TIMER1 CH0 input capture configuration */
    timer_icinitpara.icpolarity  = TIMER_IC_POLARITY_RISING;         //捕获极性,上升沿捕获
    timer_icinitpara.icselection = TIMER_IC_SELECTION_DIRECTTI;      //通道输入模式选择
    timer_icinitpara.icprescaler = TIMER_IC_PSC_DIV1;                //分频
    timer_icinitpara.icfilter    = 0x0;                              //滤波
    timer_input_capture_config(TIMER1, TIMER_CH_0, &timer_icinitpara);
 
    /* auto-reload preload enable */
    timer_auto_reload_shadow_enable(TIMER1);//自动重载使能
    /* clear channel 0 interrupt bit */
    //timer_interrupt_flag_clear(TIMER1,TIMER_INT_FLAG_CH0);//CH0 通道中断清除
    /* channel 0 interrupt enable */
    //timer_interrupt_enable(TIMER1,TIMER_INT_CH0);//CH0 通道中断使能
     /* TIMER1 counter enable */
    timer_enable(TIMER1);
 	//NVIC_SetPriority(TIMER1_IRQn,0);
    //NVIC_EnableIRQ(TIMER1_IRQn);
}

/**
 * 获取脉冲数量
*/
uint32_t bsp_timer1_get_count(void)
{
    return (timer_channel_capture_value_register_read(TIMER1, TIMER_CH_0) + 1);
}

/**
 * 设置脉冲数量
*/
void bsp_timer1_set_count(uint32_t val)
{
    timer_channel_output_pulse_value_config(TIMER1, TIMER_CH_0, val);
}
